﻿using System;
using System.Windows.Input;

namespace SvgViewer.Core;

/// <summary>
/// 单参数命令基类
/// </summary>
public class RelayCommand : ICommand
{
    private readonly Action<object>    execute;
    private readonly Predicate<object> canExecute;

    /// <summary>
    /// 构造
    /// </summary>
    /// <param name="execute">命令执行方法</param>
    /// <param name="canExecute">是否允许执行方法</param>
    public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
    {
        this.execute    = execute;
        this.canExecute = canExecute;
    }

    /// <summary>
    /// 检查命令是否可执行
    /// </summary>
    /// <param name="parameter">检查参数</param>
    /// <returns>可执行返回true</returns>
    public bool CanExecute(object parameter)
    {
        return canExecute == null || canExecute(parameter);
    }

    /// <summary>
    /// 执行命令方法
    /// </summary>
    /// <param name="parameter">方法所需参数</param>
    public void Execute(object parameter)
    {
        execute(parameter);
    }

    /// <summary>
    /// 
    /// </summary>
    public event EventHandler CanExecuteChanged {
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }
}